/**
 * 
 */
package edu.umd.clip.lm.model.data;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class AbstractTrainingDataNode {
	private int nodeId;
	private int numData;
	
	private static final int HEADER_SIZE = 8;
	
	protected AbstractTrainingDataNode(ReadableByteChannel channel) throws IOException {
		readHeader(channel);
	}
	
	protected AbstractTrainingDataNode(int nodeId, int numData) {
		this.nodeId = nodeId;
		this.numData = numData;
	}

	public int getNodeId() {
		return nodeId;
	}

	public void setNodeId(int nodeId) {
		this.nodeId = nodeId;
	}

	public void readHeader(ObjectInput in) throws IOException {
		nodeId = in.readInt();
	}

	public void writeHeader(ObjectOutput out) throws IOException {
		out.writeInt(nodeId);
	}

	public void readHeader(ReadableByteChannel in) throws IOException {
		ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);
		long read = in.read(buffer);
		if (read == -1) {
			throw new EOFException();
		}
		buffer.flip();
		nodeId = buffer.getInt();
		numData = buffer.getInt();
	}
	
	public void writeHeader(WritableByteChannel out) throws IOException {
		ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);
		buffer.putInt(nodeId);
		buffer.putInt(numData);
		buffer.flip();
		out.write(buffer);
	}

	public int getNumData() {
		return numData;
	}

	@Override
	public String toString() {
		return "TrainingDataNode [nodeId=" + nodeId + ", numData="
				+ numData + "]";
	}
}
